package main

import (
	"fmt"
	"flag"
	"net"
	"io/ioutil"
	"encoding/json"
	"strings"
	"strconv"
	iplocation "gitee.com/thubcc/blockchain/iplocationservice"
)

var (
	argInFile  = flag.String("i",".ethereum/node.json","node json")
	argOutFile = flag.String("o",".ethereum/addr.js","addr js file")
	argDBFile  = flag.String("d",".resources/GeoLite2-City.mmdb","addr db file")
)

type Rec struct {
	IP string
	Port int64
	Longitude,Latitude float64
}

func parse(addr string,db *iplocation.IPDB) (*Rec,error) {
	r := new(Rec)
	addrIp := strings.Split(addr,":")
	ipstr := string(addrIp[0])
	if len(addrIp)!=2 {
		return nil,fmt.Errorf("Bad address")
	}
	port,err := strconv.ParseInt(addrIp[1],10,64)
	if len(addrIp)!=2 {
		return nil,fmt.Errorf("Bad address")
	}
	r.Port = port
	ip := net.ParseIP(ipstr)
	if ip == nil {
		return nil,fmt.Errorf("Parse Ip failure")
	}
	r.IP = ipstr
	record, err := db.Reader.City(ip)
	if err != nil {
		return nil,fmt.Errorf("locate %s failure, %v",addr,err)
	}
	r.Longitude, r.Latitude = record.Location.Longitude, record.Location.Latitude
	return r, nil
}

func main() {
	flag.Parse()
	db := &iplocation.IPDB{DBFile:*argDBFile}

	err := db.Init()
	if err != nil {
		fmt.Printf("open db failure: %v\n",err)
		return
	}
	defer db.Close()

	buf,err := ioutil.ReadFile(*argInFile)
	if err != nil {
		fmt.Printf("open input failure: %v\n",err)
		return
	}

	var log = make(map[string]string)
	err = json.Unmarshal(buf,&log)
	if err != nil {
		fmt.Printf("Unmarshal failure: %v\n",err)
		return
	}

	var result = make(map[string]Rec)

	for k,v := range log {
		r,err := parse(v,db)
		if err != nil {
			fmt.Println("Parse error",err)
		}
		result[k] = *r
	}

	buf,err = json.MarshalIndent(result,"","  ")
	if err != nil {
		fmt.Println("Dump to file error")
	}
	arg := "var IPLocation ="
	if err = ioutil.WriteFile(*argOutFile,append([]byte(arg),buf...),0755); err!=nil {
		fmt.Println("write to file error")
	}
}